#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pymysql
import json
import traceback

#保存指标数据到数据库
#输入：
#metric_dict——适配于rca_entry()中解析后的adict格式，包含各个指标数据和timestamp信息
#machine_IP——机器IP
#abnormal_name——缺省None，即非标注数据；如果要输入这一项，需要参考已录入的异常表abnormal_info（包含异常名和异常描述的数据库表）
#返回bool值，true代表成功存入数据库，false代表存储失败
def save_metrics(metric_dict,machine_IP,abnormal_name = None):
    try:
        timestamp_occur = float(metric_dict["timestamp"])
        timestamp_start = float(metric_dict["base"]["timestamp"][0])
        timestamp_end = float(metric_dict["base"]["timestamp"][-1])
        return _save_metrics(abnormal_name,machine_IP,timestamp_occur,timestamp_start,timestamp_end,metric_dict)
    except:
        traceback.print_exc()
        return False

#save metrics into table abnormal_data(in database sysom)
def _save_metrics(abnormal_name,machine_IP,timestamp_occur,timestamp_start,timestamp_end,metric_dict):
    try:
        metric_data_json = json.dumps(metric_dict,ensure_ascii=False)
        sql = ""
        if abnormal_name is not None:
            sql = "insert into abnormal_data (abnormal_name,machine_IP,timestamp_occur,timestamp_start,timestamp_end,metric_data) values(\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\')"%(abnormal_name.decode("utf-8"),machine_IP,timestamp_occur,timestamp_start,timestamp_end,metric_data_json)
        else:
            sql = "insert into abnormal_data (abnormal_name,machine_IP,timestamp_occur,timestamp_start,timestamp_end,metric_data) values(\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\')"%("unclear",machine_IP,timestamp_occur,timestamp_start,timestamp_end,metric_data_json)
        conn=pymysql.connect(host="localhost",port=3306,user="root",passwd="",db="sysom",charset="utf8")
        cursor=conn.cursor()
        cursor.execute(sql)

        cursor.close()
        conn.commit()
        conn.close()
        #print("Save success")
        return True
    except:
        traceback.print_exc()
        return False

#return each abnormal_name and corresponding metrics' datas
def get_all_metrics():
    try:
        conn=pymysql.connect(host="localhost",port=3306,user="root",passwd="",db="sysom",charset="utf8")
        cursor = conn.cursor()
        sql = "select * from abnormal_data"
        cursor.execute(sql)
        fetch_all=cursor.fetchall()
        cursor.close()
        conn.commit()
        conn.close()

        #print(len(fetch_all))
        #print(len(fetch_all[0]))
        #for i in range(len(fetch_all[0])):
        #    print(type(fetch_all[0][i]))

        adict = {}
        for i in range(len(fetch_all)):
            name = fetch_all[i][0]
            metric = json.loads(fetch_all[i][len(fetch_all[i])-1])
            if name not in adict.keys():
                adict[name] = []
                adict[name].append(metric)
            else:
                adict[name].append(metric)
        return adict
    except:
        traceback.print_exc()
        return False
